package cn.cdeden.aiqa.controller;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

import cn.cdeden.aiqa.domain.WikiRecord;
import cn.cdeden.aiqa.domain.bo.ChatRecordQueryParam;
import cn.cdeden.aiqa.domain.bo.WikiRecordBo;
import cn.cdeden.aiqa.domain.vo.WikiRecordVo;
import cn.cdeden.aiqa.service.IWikiRecordService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import cn.cdeden.common.idempotent.annotation.RepeatSubmit;
import cn.cdeden.common.log.annotation.Log;
import cn.cdeden.common.web.core.BaseController;
import cn.cdeden.common.mybatis.core.page.PageQuery;
import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.log.enums.BusinessType;
import cn.cdeden.common.excel.utils.ExcelUtil;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * AI提问记录
 * 前端访问路由地址为:/aiqa/record
 *
 * @author Nick
 * @date 2024-12-12
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/wiki/record")
public class WikiRecordController extends BaseController {

    private final IWikiRecordService wikiRecordService;

    /**
     * 查询AI提问记录列表
     */
    @GetMapping("/list")
    public TableDataInfo<WikiRecordVo> list(WikiRecordBo bo, PageQuery pageQuery) {
        return wikiRecordService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出AI提问记录列表
     */
    @Log(title = "AI提问记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(WikiRecordBo bo, HttpServletResponse response) {
        List<WikiRecordVo> list = wikiRecordService.queryList(bo);
        ExcelUtil.exportExcel(list, "AI提问记录", WikiRecordVo.class, response);
    }

    /**
     * 获取AI提问记录详细信息
     *
     * @param id 主键
     */
    @GetMapping("/{id}")
    public R<WikiRecordVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(wikiRecordService.queryById(id));
    }

    @GetMapping(value = "/getAssistant")
    @Log(title = "查询单条（助手）", businessType = BusinessType.OTHER)
    public R<List<WikiRecordVo>> queryByAssistantId(ChatRecordQueryParam query) {
        return R.ok(wikiRecordService.queryByAssistantId(query));
    }

    /**
     * 新增AI提问记录
     */
    @Log(title = "AI提问记录", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<WikiRecord> add(@RequestParam("file") MultipartFile file, @RequestParam(value = "expert", required = false) String expert) {

        if (file.isEmpty()) {
            return R.fail("File is empty");
        }

        try {
            // 读取文件内容
            String content = new String(file.getBytes(), StandardCharsets.UTF_8);

            // 解析 JSON 字符串为对象
            ObjectMapper objectMapper = new ObjectMapper();
            WikiRecordBo bo = objectMapper.readValue(content, WikiRecordBo.class);

            return R.ok(wikiRecordService.insertByBo(bo, expert));
        } catch (IOException e) {
            e.printStackTrace();
            return R.fail("Failed to parse file");
        }

    }


    /**
     * 修改AI提问记录
     */
    @Log(title = "AI提问记录", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<WikiRecord> edit(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return R.fail("File is empty");
        }

        try {
            // 读取文件内容
            String content = new String(file.getBytes(), StandardCharsets.UTF_8);

            // 解析 JSON 字符串为对象
            ObjectMapper objectMapper = new ObjectMapper();
            WikiRecordBo bo = objectMapper.readValue(content, WikiRecordBo.class);

            return R.ok(wikiRecordService.updateByBo(bo));
        } catch (IOException e) {
            e.printStackTrace();
            return R.fail("Failed to parse file");
        }
    }

    /**
     * 删除AI提问记录
     *
     * @param ids 主键串
     */
    @Log(title = "AI提问记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(wikiRecordService.deleteWithValidByIds(List.of(ids), true));
    }
}
